<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;
use CodeItNow\BarcodeBundle\Utils\BarcodeGenerator;

class MealOrder extends Model
{
    const CREATED_AT = 'insert_time';
    const UPDATED_AT = 'update_time';
    /**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'lexiang_meal_order';

    protected $primaryKey = 'order_id';

    public $timestamps = false;
    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = ['shops_id','users_id','cates_id','cards_id','order_status','insert_time','update_time'];

    /**
     * 商铺总订单数
     */
    public function orderTotal($shopid)
    {
        return self::where('shops_id',$shopid)->count();
    }

    /**
     * 商铺订单列表
     */
    public function list($shopid=false,$page=15,$keyword=false,$sx=false)
    {
        return MealOrder::where(function($q)use($shopid,$keyword,$sx){
            $w = [];
            $s = [];
            $r = [];
            if($shopid){
                $w[] = ['lexiang_meal_order.shops_id','=',$shopid];
            }
            if($sx=='day'){
                $w[] = ['lexiang_meal_order.insert_time','>',strtotime(date('Y-m-d 00:00:00'))];
                $w[] = ['lexiang_meal_order.insert_time','<',strtotime(date('Y-m-d 23:59:59'))];
            }
            if($keyword){
                $s[] = ['lexiang_user.tel','=',$keyword];
                $r[] = ['lexiang_user.nicename','like','%'.$keyword.'%'];
            }
            return $q->where(array_merge($w,$s))->orWhere(array_merge($w,$r));
        })
        ->where('lexiang_meal_order.order_status','>',-3)
        ->leftJoin('lexiang_meal_shop','lexiang_meal_shop.shop_id','=','lexiang_meal_order.shops_id')
        ->leftJoin('lexiang_user','lexiang_user.user_id','=','lexiang_meal_order.users_id')
        ->selectRaw('lexiang_meal_shop.shop_name,lexiang_meal_order.*,lexiang_user.nicename,null as cateslist,null as help_user_name,lexiang_meal_shop.shop_tel,lexiang_user.tel as user_tel')
        ->orderBy('lexiang_meal_order.insert_time','desc')
        ->paginate($page,['shopid','extract-page','cate-page'],'order-page');
    }

    /**
     * 用户订单列表
     */
    public static function userList($userid=false,$page=15)
    {
        $orders = MealOrder::where(function($q)use($userid){
            if($userid){
                return $q->where('lexiang_meal_order.users_id',$userid);
            }else{
                return $q;
            }
        })
        ->leftJoin('lexiang_meal_shop','lexiang_meal_shop.shop_id','=','lexiang_meal_order.shops_id')
        ->leftJoin('lexiang_user','lexiang_user.user_id','=','lexiang_meal_order.users_id')
        ->select('lexiang_meal_shop.shop_name','lexiang_meal_order.*','lexiang_user.nicename')
        ->orderBy('lexiang_meal_order.insert_time','desc')
        ->paginate($page,['userid','card-page'],'order-page');
        return $orders;
    }

    /**
     * 下单
     */
    public function postOrder($data,$paystatus=false)
    {
        DB::beginTransaction();
        $nowTime = time();
        $this->order_number = $this->createOrderNumber();
        $this->cate_num = $data['cate_num'];
        $this->shops_id = $data['shops_id'];
        $this->users_id = $data['users_id'];
        $this->cates_id = $data['cates_id'];
        if($paystatus){
            $this->order_status = -1;
        }else{
            $this->order_status = 0;
        }
        $this->insert_time = $nowTime;
        $this->cards_id = $data['cards_id'];
        $this->meal_order_price = $data['meal_order_price'];
        $this->order_type = $data['order_type'];
        $this->order_sernum = MealShop::getnumber($data['shops_id']);
        $this->order_remarks = $data['order_remarks'];
        $this->help_user_id = $data['help_user_id'];
        $this->cate_list = $data['cate_list'];
        $this->help_state = 0;
        $this->pay_price = $data['pay_price'];
        $this->cart_cates = $data['cart_cates'];
        $this->markup = (int)$paystatus;
        if($this->save()){
            DB::commit();
            if($this->order_type != 2 && $this->order_type != 1 && $this->order_status != -1){
                $this->sendWebSocket($this->order_id,$data['shops_id']);
            }
            return [
                'success'=>true,
                'resultCode'=>1,
                'msg'=>'保存成功',
                'data'=>[
                    'order_number'=>$this->order_number,
                    'order_id'=>$this->order_id,
                ]
            ];
        }else{
            DB::rollback();
            return [
                'success'=>false,
                'resultCode'=>-1,
                'msg'=>"保存出错，请稍后再试！"
            ];
        }
    }

    
    
    /**
     * 生成订单号
     */
    public function createOrderNumber()
    {
        return time().rand(11111,99999);
    }

    public function getScancodeAttribute($v)
    {
        $barcode = new BarcodeGenerator();
        $barcode->setText("js_".$this->order_number);
        $barcode->setType(BarcodeGenerator::Code128);
        $barcode->setScale(2);
        $barcode->setThickness(25);
        $barcode->setFontSize(0);
        return $barcode->generate();
    }

    public function sendWebSocket($orderid,$shopid)
    {
        $nowTime = time();
        curl_post('http://47.104.173.240:9501',[
            'status'=>'0',
            'action'=>'DownOrder',
            'randstr'=>$nowTime,
            'mdkey'=>strtoupper(md5($nowTime.env('WEBKEY'))),
            'order_id'=>$orderid,
            'shop_id'=>$shopid,
        ]);
    }

    /**
     * 扫码提醒
     */
    public function scanWebSocket($orderid,$shopid,$num)
    {
        $nowTime = time();
        curl_post('http://47.104.173.240:9501',[
            'status'=>'1',
            'action'=>'KnotOrder',
            'num'=>$num,
            'randstr'=>$nowTime,
            'mdkey'=>strtoupper(md5($nowTime.env('WEBKEY'))),
            'order_id'=>$orderid,
            'shop_id'=>$shopid,
        ]);
    }

    public function getMealOrderPriceAttribute($v){
        return $v;
    }

    /**
     * 转购物车数据
     */
    public function getCartCatesAttribute($v)
    {
        if(empty($v)){
            return $v;
        }
        return json_decode($v,true);
    }

    /**
     * 商铺名
     */
    public function getShopNameAttribute($v)
    {
        return MealShop::where('shop_id',$this->shops_id)->value('shop_name') ?? '未获取';
    }

    public function getDeliveryIfAttribute($v)
    {
        $statusde = [0=>'到店吃',1=>'打包带走',2=>'朋友帮带','乐享专送'];
        return $statusde[$this->order_type] ?? '自取';
    }

    public function getDeliveryInfoAttribute($v)
    {
        if($this->order_type == 2){
            return HelpAddress::where('user_id',$this->users_id)->first()->toArray();
        }else{
            return [];
        }
    }

    public function getCateslistAttribute($v)
    {
        if(empty($this->cate_list)){
            return MealCate::where('cate_id',$this->cates_id)->value('cate_name');
        }
        $cates = explode(',', $this->cate_list);
        $catenames = MealCate::whereIn('cate_id',$cates)->pluck('cate_name')->toArray();
        return implode('，', $catenames);
    }

    /**
     * 帮带手机号
     */
    public function getHelpTelAttribute($v)
    {
        return User::where('user_id',$this->help_user_id)->value('tel');
    }

    public function getHelpUserNameAttribute($v)
    {
        return User::where('user_id',$this->help_user_id)->value('nicename');
    }

    public function getInsertTimeAttribute($v)
    {
        return date('Y-m-d H:i',$v);
    }

    public function getCreatedAtAttribute($v)
    {
        return $this->insert_time;
    }

    public function getCateImgQuAttribute($v)
    {
        return 'https://jiashilexiang.oss-cn-beijing.aliyuncs.com/MealCateImgs'.$this->cate_imgs;
    }
}
